package com.qxzn.app.page.robot;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.RobotDeviceListBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.R;
import com.qxzn.app.page.view.MaxHeightRecyclerView;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RobotHelper {

    public RobotHelper(FragmentActivity activity) {
        this.activity = activity;
    }

    private FragmentActivity activity;

    public void startAddRobot() {
        startActivity(activity, AddRobotQRActivity.class);
    }


    public static void startActivity(FragmentActivity activity, Class activityClass) {
        PermissionHelper.startActivity(activity, activityClass);
    }

    public void startSwitchRobot(String robotName, int style) {
        showProgress();
        HttpRequest.getService().getRobotDeviceList().enqueue(new Callback<RobotDeviceListBean>() {
            @Override
            public void onResponse(Call<RobotDeviceListBean> call, Response<RobotDeviceListBean> response) {
                RobotDeviceListBean baseBean = response.body();
                hideProgress();
                if (baseBean.getCode() == 200) {
                    List<RobotDeviceListBean.DataBean> deviceList = baseBean.getData();
                    if (deviceList != null) {
                        showSwitchDialog(deviceList, robotName);
                    }
                } else if (!TextUtils.isEmpty(baseBean.getMsg())) {
                    ToastUtil.showTextToast(activity, baseBean.getMsg());
                }
            }

            private void showSwitchDialog(List<RobotDeviceListBean.DataBean> robotList, String robotName) {
                final Dialog dialog = new Dialog(activity, R.style.FullDialogStyle);
                Window window = dialog.getWindow();
                if (window != null) {
                    window.getDecorView().setPadding(0, 0, 0, 0);
                    WindowManager.LayoutParams layoutParams = window.getAttributes();
                    layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
//                    layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT; // 设置高度会导致状态栏变黑问题
                    window.setAttributes(layoutParams);
                }

                View contentView = LayoutInflater.from(activity).inflate(
                        style == 0 ? R.layout.switch_robot_dialog_top : R.layout.switch_robot_dialog_bottom,
                        null);
                View.OnClickListener onClickListener = v -> {
                    int id = v.getId();
                    dialog.dismiss();
                    if (id == R.id.iv_add_dialog || id == R.id.add_robot_spinner) {
                        startAddRobot();
                    } else if (id == R.id.robot_settings_spinner) {
                        activity.startActivity(new Intent().setComponent(new ComponentName(activity, "com.qxzn.module.mine.activity.MoreSettingsActivity")));
                    }
                };
                if (style == 0) {
                    TextView name = contentView.findViewById(R.id.robot_name);
                    name.setOnClickListener(onClickListener);
                    name.setText(robotName);
                    contentView.findViewById(R.id.iv_add_dialog).setOnClickListener(onClickListener);
                }
                contentView.findViewById(R.id.add_robot_spinner).setOnClickListener(onClickListener);
                contentView.findViewById(R.id.robot_settings_spinner).setOnClickListener(onClickListener);
                contentView.findViewById(R.id.bg).setOnClickListener(onClickListener);
                MaxHeightRecyclerView robotSpinnerRecycler = contentView.findViewById(R.id.robot_spinner_recycler);
                LRecyclerViewAdapter robotsAdapter = new LRecyclerViewAdapter(new RobotSpinnerAdapter(robotList));
                robotsAdapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        RobotDeviceListBean.DataBean item = (RobotDeviceListBean.DataBean) view.getTag();
                        if (item == null || "1".equals(item.getCurrent())) {
                            return;
                        }
                        showProgress();
                        JSONObject params = new JSONObject();
                        params.put("username", SharePreferenceUtil.getUserName(activity));
                        params.put("device_id", item.getDevice_id());
                        changeRobot(params, item.getDevice_id());
                    }

                    private void changeRobot(JSONObject params, String device_id) {

                        HttpRequest.getService().changeRobot(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
                            @Override
                            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                                BaseBean baseBean = response.body();
                                hideProgress();
                                if (baseBean != null) {
                                    if (baseBean.getCode() == 200) {
                                        for (RobotDeviceListBean.DataBean dataBean : robotList) {
                                            if ((device_id + "").equals(dataBean.getDevice_id())) {
                                                SharePreferenceUtil.setDeviceId(activity, device_id);
                                                SharePreferenceUtil.setDeviceName(activity, dataBean.getName());
                                                EventBusManager.post(new EventBusBean.Builder().id(Constant.EventBusId.SWITCH_DEVICE_ID).build());
                                                dialog.dismiss();
                                            }
                                        }
                                        return;
                                    }
                                }
                                if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                                    ToastUtil.showTextToast(activity, baseBean.getMsg());
                                } else {
                                    ToastUtil.showTextToast(activity, "切换失败，请重试");
                                }
                            }

                            @Override
                            public void onFailure(Call<BaseBean> call, Throwable t) {
                                hideProgress();
                                ToastUtil.showTextToast(activity, activity.getString(R.string.network_error));
                            }
                        });

                    }
                });
                robotSpinnerRecycler.setAdapter(robotsAdapter);
                robotSpinnerRecycler.setPullRefreshEnabled(false);
                robotSpinnerRecycler.setLoadMoreEnabled(false);

                dialog.setContentView(contentView);
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);

                dialog.show();
            }

            @Override
            public void onFailure(Call<RobotDeviceListBean> call, Throwable t) {
                hideProgress();
                ToastUtil.showTextToast(activity, activity.getString(R.string.network_error));
            }
        });
    }

    private void hideProgress() {
        if (activity instanceof BaseActivity)
            ((BaseActivity) activity).hideProgress();
    }

    private void showProgress() {
        if (activity instanceof BaseActivity)
            ((BaseActivity) activity).showProgress();
    }
}
